<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件

/**
 * 生成令牌
 * @return type 
 */
function generateToken($str)
{
    $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
    $tokenSalt = config('secure.token_salt');
    return strtoupper(md5($str . $timestamp . $tokenSalt));
}

/**
 * @param string $url post请求地址
 * @param array $params
 * @return mixed
 */
function curl_post($url, array $params = array (), $token = '')
{
    $data_string = json_encode($params);
    $ch = curl_init();
//   设置url
    curl_setopt($ch, CURLOPT_URL, $url);
//    移除返回的头信息
    curl_setopt($ch, CURLOPT_HEADER, 0);
//    信息以字符串返回
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//    在尝试连接时等待的秒数
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//    请求类型,true为post
    curl_setopt($ch, CURLOPT_POST, 1);
//    证书校验
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//    传送数据
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//    设置 HTTP 头字段的数组
    $header = array (
        'Content-Type: application/json'
    );
    if (!empty($token))
    {
        $header['token'] = "token:$token";
    }
    curl_setopt(
            $ch, CURLOPT_HTTPHEADER, $header
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

function curl_post_raw($url, $rawData)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
    curl_setopt(
            $ch, CURLOPT_HTTPHEADER, array (
        'Content-Type: text'
            )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

/**
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 */
function curl_get($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++)
    {
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}

function fromArrayToModel($m, $array)
{
    foreach ($array as $key => $value)
    {
        $m[$key] = $value;
    }
    return $m;
}

/**
 * 加密密码
 * @param type $str
 * @return type
 */
function encrypt_password($str)
{
    return password_hash($str,PASSWORD_DEFAULT);
}

/**
 * 获取某月开头结尾
 * @access public
 * @param $his 设置 "00:00:00"就是从第一天零时开始
 * @param $type 决定返回的是日期还是时间戳,默认日期
 * @param $today_flag 最后一天是月末还是今天,默认今天
 * @return 
 */
function get_the_month($date, $his = "00:00:00", $type = "date", $today_flag = FALSE)
{
    $lastday = $firstday = date('Y-m-01 ' . $his, strtotime($date));
    $next_month_final_day = strtotime("$firstday +1 month -1 second");
    $today = time();
    if ($today < $next_month_final_day && $today_flag && strtotime($date) < $today)
    {
        $lastday = date('Y-m-d ' . "23:59:59", $today);
    }
    else
    {
        $lastday = date('Y-m-d ' . "23:59:59", $next_month_final_day);
    }
    if ($type != "date")
    {
        $firstday = strtotime($firstday);
        $lastday = strtotime($lastday);
    }
    return array ( $firstday, $lastday );
}

/**
 * 返回数组指定字段的值组成的数组
 * @param $array array 原数组
 * @param $key string 组成新数组的主键的字段
 * @return array
 */
function array_under_reset($array, $key = "id")
{
    if (!is_array($array)) return $array;
    $new_array = [];
    foreach ($array as $k => $val)
    {
        if (isset($val[$key]))
        {
            $new_key = $val[$key];
            $new_array[$new_key] = $val;
        }
    }
    return $new_array;
}

/**
 * 使用$key_map替换数组中的索引名字
 * @param array $source_arr 原数组
 * @param string $key_map 索引名映射数组
 * @return array $des_arr  目标数组
 */
function array_keys_replace(Array &$source_arr, Array $key_map = [])
{
    if (empty($key_map))
    {
        return $source_arr;
    }
    foreach ($source_arr as $key => $value)
    {
        if (isset($key_map[$key]))
        {
            $source_arr[$key_map[$key]] = $value;
            unset($source_arr[$key]);
        }
    }
    return $source_arr;
}

/**
 * array_merge但是保留key(当索引是数字是 array_merge会重新设置索引)
 * @param array $source_arr1 数组1
 * @param string $source_arr2 数组2
 * @return array 目标数组
 */
function array_merge_plus(Array $source_arr1)
{
    $args_num = func_num_args();
    $args_arr = func_get_args();
    for ($i = 1; $i < $args_num; $i++)
    {
        foreach ($args_arr[$i] as $key => $value)
        {
            $source_arr1[$key] = $value;
        }
    }
    return $source_arr1;
}

/**
 * 返回数组第一个元素
 * @param $array array 原数组
 * @return array
 */
function array_one($array)
{

    if (!is_array($array)) return $array;
    return array_shift($array);
}

/**
 * 转化两位小数金额 (返回float)
 * @param $float double 金额
 * @param $size int 保留几位小数，默认2位
 * @param $clear boolean 是否清除右侧末尾的0
 * @return double or int
 */
function money_float($float, $size = 2, $div = 1)
{
    if (is_array($float))
    {
        $return = [];
        foreach ($float as $key => $value)
        {
            $return[$key] = money_float($value, $size, $div);
        }
        return $return;
    }
    $float = (float) $float;
    $float = $float / $div;
    $float = sprintf('%.' . $size . 'f', $float);
    return (float) $float;
}

/**
 * 转换数组为饼图可用格式
 * @param array $arr
 * @param type $mode 0标题位置后面跟着数字,1标题位置仅标题
 * @return Arr
 */
function to_pie(Array $arr, $mode = 0)
{
    $formatPieChart = [];
    foreach ($arr as $key => $value)
    {
        $value = money_float($value);
        $name = $key;
        if ($mode == 0)
        {
            $name = $key . "     " . $value;
        }
        $num = $value;
        $formatPieChart[] = [ $name, $num ];
    }
    return $formatPieChart;
}

/**
 * 提取数组中的部分字段
 * @param type $source_arr
 * @param type $key
 * @return type
 */
function array_column_plus($source_arr, $key)
{
    if (func_num_args() >= 2 || is_array($key))
    {
        $args = is_array($key) ? $key : array_slice(func_get_args(), 1, func_num_args());
        $destination = array_map(function ($one) use ($args) {
            $temp = [];
            foreach ($args as $key => $value)
            {
                $temp[$value] = $one[$value];
            }
            return $temp;
        }, $source_arr);
        return $destination;
    }
    else
    {
        return array_column($source_arr, $key);
    }
}

/**
 * 输出数组
 */
function array_dump($array)
{
    foreach ($array as $key => $value)
    {
        echo "'$key'", "=>", "'$value',<br>";
    }
}

/**
 * 数据按字段分组
 * @param type $arr
 * @param type $key
 * @return type
 */
function array_group_plus($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value)
    {
        $new_key = isset($value[$key]) ? $value[$key] : '';
        $grouped[$new_key][] = $value;
    }
    if (func_num_args() > 2)
    {
        $args = func_get_args();
        foreach ($grouped as $key => $value)
        {
            $parms = array_merge([ $value ], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}

/**
 * 按照key提取数组中的元素
 * @param array $source_arr 原数组
 * @param string $key_arr 需要key组成的数组
 * @return $mode 数组
 */
function array_field(Array $source_arr, $key_arr = [])
{
    if (empty($key_arr))
    {
        return array_values($source_arr);
    }
    if (is_string($key_arr))
    {
        $key_arr = [ $key_arr ];
    }
    $new_list = [];
    foreach ($source_arr as $key => $value)
    {
        if (in_array($key, $key_arr))
        {
            $new_list[$key] = $value;
        }
    }
    return $new_list;
}

/**
 * 输出一个或多个内容,终止运行
 */
function halt_plus($source = '')
{
    $args_num = func_num_args();
    $args = func_get_args();
    for ($i = 0; $i < $args_num - 1; $i++)
    {
        dump($args[$i]);
    }
    return halt($args[$i]);
}

/**
 *  生成带该页面get的链接
 * @param string $str 控制器/方法
 * @param type 需要设置的get参数
 * @return url 生成的链接
 */
function merge_url($str, $arr = [], $method = "get.")
{
    return url($str, array_merge(input($method), $arr));
}

/**
 * 日期(时间戳)比较,$date1>$date2 返回true
 * @param type $date1
 * @param type $date2
 * @return type
 */
function date_compare($date1, $date2)
{
    $date1 = to_date($date1);
    $date2 = to_date($date2);
    $time1 = to_timestamp($date1);
    $time2 = to_timestamp($date2);
    return $time1 > $time2;
}

/**
 * 返回所在年的数组
 * @param type $date
 * @return type
 */
function current_year_date_arr($date)
{
    $time_arr = [
        to_date($date, "Y-1-1 00:00:00"),
        to_date($date, "Y-12-31 23:59:59"),
    ];
    return $time_arr;
}

/**
 * 返回所在月的数组
 * @param type $date
 * @return type
 */
function current_month_date_arr($date)
{
    $time_arr = [
        to_date($date, "Y-n-1 00:00:00"),
        to_date($date, "Y-n-t 23:59:59"),
    ];
    return $time_arr;
}

/**
 * 返回所在周的数组
 * @param type $date
 * @return type
 */
function current_week_date_arr($date)
{
    $week_day = to_date($date, 'w') - 1;
    $start_time = strtotime($date . " -{$week_day} day");
    $end_time = strtotime(" +6 days", $start_time);
    $time_arr = [
        to_date($start_time, "Y-n-j 00:00:00"),
        to_date($end_time, "Y-n-j 23:59:59"),
    ];
    return $time_arr;
}

/**
 * 返回去年的数组
 * @param type $date
 * @return type
 */
function last_year_date_arr($date)
{
    $time_arr = current_year_date_arr($date);
    $time_arr = [
        to_date(to_timestamp($time_arr[0], "-1 year")),
        to_date(to_timestamp($time_arr[1], "-1 year")),
    ];
    return $time_arr;
}

/**
 * 返回上月的数组
 * @param type $date
 * @return type
 */
function last_month_date_arr($date)
{
    $time_arr = current_month_date_arr($date);
    $time_arr = [
        to_date(to_timestamp($time_arr[0], "-1 month"), "Y-n-1 00:00:00"),
        to_date(to_timestamp($time_arr[0], "-1 month"), "Y-n-t 23:59:59"),
    ];
    return $time_arr;
}

/**
 * 返回上周的数组
 * @param type $date
 * @return type
 */
function last_week_date_arr($date)
{
    $time_arr = current_week_date_arr($date);
    $time_arr = [
        to_date(to_timestamp($time_arr[0], "-7 days"), "Y-n-j 00:00:00"),
        to_date(to_timestamp($time_arr[1], "-7 days"), "Y-n-j 23:59:59"),
    ];
    return $time_arr;
}

/**
 * 转换为日期
 * @param type $source 时间戳或者日期,必须完整,如年月日,年月日时分秒(数组可以批量转换)
 * @param string $format ,格式字符串
 * @return mixed
 */
function to_date($source = '', $format = "Y-m-d H:i:s")
{
    if (empty($source))
    {
        $source = time();
    }
    if (is_array($source))
    {
        foreach ($source as $key => $value)
        {
            $source[$key] = to_date($value, $format);
        }
    }
    else
    {
        if (strlen($source) <= 4)
        {
            $source .= "年";
        }
        if (!is_numeric($source))
        {
            $contrast = [
                "年|月" => '-',
                "日|(日\s)" => ' ',
                "时|分" => ':',
                "秒" => '',
                "\-$" => '-1',
                ":$" => ':0',
            ];
            $source = mb_strtr($source, $contrast);
            $source = strtotime($source) ? strtotime($source) : null;
        }
        return date($format, $source);
    }
    return $source;
}

/**
 *  多字节的字符串替换
 * @param type $source
 * @param array $contrast
 * @param type $encoding
 * @return type
 */
function mb_strtr($source, array $contrast, $encoding = "utf-8")
{
    mb_regex_encoding($encoding);
    foreach ($contrast as $key => $value)
    {
        $source = mb_ereg_replace($key, $value, $source);
    }
    return $source;
}

/**
 * 转换为时间戳(支持数组)
 * @param type $source 日期
 * @param string $condition
 * @param type $now
 * @return type
 */
function to_timestamp($source, $condition = "", $now = null)
{
    if (is_numeric($source) || empty($source))
    {
        return $source;
    }
    //添加空格
    if (!empty($condition))
    {
        $condition = " " . $condition;
    }
    if (is_array($source))
    {
        if (!empty($source[1]) && is_array($source[1]))
        {
            //between 格式
            $resoruce = $source;
            $source = $source[1];
        }
        $source = to_date($source);
        foreach ($source as $key => $value)
        {
            if (!empty($now))
            {
                $source[$key] = strtotime($value . "$condition", $now);
            }
            else
            {
                $source[$key] = strtotime($value . "$condition");
            }
        }
        if (!empty($resoruce[1]) && is_array($resoruce[1]))
        {
            //between 格式
            $resoruce[1] = $source;
            $source = $resoruce;
        }
    }
    else
    {
        $source = to_date($source);
        if (!empty($now))
        {
            $source = strtotime($source . "$condition", $now);
        }
        else
        {
            $source = strtotime($source . "$condition");
        }
        return $source;
    }
    return $source;
}
